package cn.jzq.sort;

import cn.jzq.util.ArrayTool;
import org.omg.PortableInterceptor.INACTIVE;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author jzq 945048240@qq.com
 */
public class SortTest
{
    public static Integer LENGTH = 1234;
    public static Integer MAX_NUMBER = 10000;
    public static Integer COUNT = 1000;

    public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException
    {

        Long insertionTimeConsuming = sortTimeConsuming(InsertionSort.class, "insertionSort");

        Long bubbleTimeConsuming = sortTimeConsuming(BubbleSort.class, "bubbleSort");

        System.out.println("insertion sort : " + insertionTimeConsuming + " ms");
        System.out.println("bubble sort : " + bubbleTimeConsuming + " ms");
    }


    /**
     * 通用的排序算法耗时计算
     *
     * @param clazz 类
     * @param methodName 方法名
     * @return 排序耗时 (ms)
     * @author jzq 945048240@qq.com
     */
    public static Long sortTimeConsuming(Class<?> clazz, String methodName) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException
    {
        Constructor constructor = clazz.getConstructor();
        constructor.setAccessible(true);
        Object obj = constructor.newInstance();
        Method method = clazz.getDeclaredMethod(methodName, Integer[].class);
        method.setAccessible(true);

        Long timeConsuming = Long.valueOf("0");
        for (int i = 0; i < COUNT; i++)
        {
            // 一个随机数组
            Integer[] array = ArrayTool.getRandomArray(LENGTH, MAX_NUMBER);
            Long startTime = System.currentTimeMillis();
            // 使用new Object[]数组将new Integer[] 进行打包成一个对象
            method.invoke(obj, new Object[]{array});
            Long endTime = System.currentTimeMillis();

            timeConsuming += endTime - startTime;
        }

        return timeConsuming;
    }
}
